﻿using System;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using System.Drawing;
using Infragistics.Win.UltraWinGrid;
using POS.BusinessComponents;
using POS.BusinessEntities;
using POS.UI.UserControls;

namespace POS.UI.Mantenimientos
{

    [Flags]
    public enum ToolBarButtons
    {
        None = 0,
        Save = 1,
        SaveClose = 2,
        Edit = 4,
        Delete = 8,
        New = 16,
        Search = 64,
        Print = 128,
        Approve = 256,
        Close = 512
    }

    public partial class MantForm: Form
    {
        #region Constructors

        protected MantForm()
        {
            InitializeComponent();
            assembly = Assembly.GetExecutingAssembly();
        }

        #endregion

        #region Declarations

        private static Stream imageStream;
        private static Assembly assembly;

        private const string NamespaceName = "POS.UI";
        protected const string GridGroupBoxText = "Arrastre una columna aquí para agrupar por esa columna";

        // Declaraciones 
        protected const string CloseText = "&Salir";
        protected const string SaveText = "&Guardar";
        protected const string SaveCloseText = "&Guardar/Salir";
        protected const string DeleteText = "&Eliminar";
        protected const string NewText = "&Nuevo";
        protected const string EditText = "E&ditar";
        protected const string SearchText = "&Buscar";
        protected const string PrintText = "&Imprimir";
        protected const string ApproveText = "&Finalizar";

        protected const string LongMoneyFormat = "#,##0.0000";
        protected const string ShortMoneyFormat = "#,##0.00";
        protected const string IntegerFormat = "#,##0";
        
        #endregion

        #region Event Handlers

        private void MantForm_Load(object sender, EventArgs e)
        {
            ConfigureToolBar(toolStrip, ToolBarButtons.Save |
                                        ToolBarButtons.SaveClose |
                                        ToolBarButtons.New |
                                        ToolBarButtons.Delete |
                                        ToolBarButtons.Close);
            ConfigureNumericTextBoxes(Controls);
        }

        protected static void ConfigureNumericTextBoxes(Control.ControlCollection controls)
        {   
            foreach (Control ctr in controls)
            {
                if (ctr is NumericTextBox)
                    ((NumericTextBox) ctr).Format = LongMoneyFormat;

                if (ctr.Controls.Count > 0)
                    ConfigureNumericTextBoxes(ctr.Controls);
            }
        }

        private void MantForm_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == Convert.ToChar(Keys.Enter) &&
                !(sender is TextBox && ((TextBox)sender).AcceptsReturn))
            {
                // Envia un Tab
                e.Handled = true;
                SendKeys.Send(Convert.ToChar(9).ToString());
            }
        }
        
        private void toolStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            switch (e.ClickedItem.Text)
            {
                case CloseText:
                    Close();
                    break;

                case SaveText:
                    if (ValidateInput())
                        Save();
                    break;

                case SaveCloseText:
                    if (ValidateInput())
                    {
                        Save();
                        Close();
                    }   
                    break;

                case DeleteText:
                    Delete();
                    break;
            }
        }


        #endregion

        #region Methods: Virtual

        protected virtual bool ValidateInput()
        {
            throw new NotImplementedException();
        }
    
        protected virtual void Save()
        {
            throw new NotImplementedException();
        }

        protected virtual void Delete()
        {
            throw new NotImplementedException();
        }

        #endregion

        #region Methods: Non-Public

        public void ShowError(string description)
        {
            MessageBox.Show(description, Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        public bool ShowQuestion(string description)
        {
            return (MessageBox.Show(description, Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes);
        }

        public void ShowConfirmation(string description)
        {
            MessageBox.Show(description, Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        public static void ConfigureToolBar(ToolStrip toolStrip, ToolBarButtons buttons)
        {
            toolStrip.Items.Clear();

            if (ContainsButton(buttons, ToolBarButtons.New))
                AddToolStripButton(toolStrip, ToolBarButtons.New);

            if (ContainsButton(buttons, ToolBarButtons.Save))
                AddToolStripButton(toolStrip, ToolBarButtons.Save);

            if (ContainsButton(buttons, ToolBarButtons.SaveClose))
                AddToolStripButton(toolStrip, ToolBarButtons.SaveClose);

            if (ContainsButton(buttons, ToolBarButtons.Delete))
                AddToolStripButton(toolStrip, ToolBarButtons.Delete);

            if (ContainsButton(buttons, ToolBarButtons.Edit))
                AddToolStripButton(toolStrip, ToolBarButtons.Edit);

            if (ContainsButton(buttons, ToolBarButtons.Search))
            {
                AddToolStripSeparator(toolStrip);
                AddToolStripButton(toolStrip, ToolBarButtons.Search);
                AddToolStripSeparator(toolStrip);
            }

            if (ContainsButton(buttons, ToolBarButtons.Print))
            {
                if (toolStrip.Items.Count > 0 && toolStrip.Items[toolStrip.Items.Count - 1].CanSelect)
                    AddToolStripSeparator(toolStrip);
                AddToolStripButton(toolStrip, ToolBarButtons.Print);
                AddToolStripSeparator(toolStrip);
            }

            if (ContainsButton(buttons, ToolBarButtons.Approve))
            {
                if (toolStrip.Items[toolStrip.Items.Count - 1].CanSelect)
                    AddToolStripSeparator(toolStrip);

                AddToolStripButton(toolStrip, ToolBarButtons.Approve);
                AddToolStripSeparator(toolStrip);
            }

            if (toolStrip.Items.Count > 0 && toolStrip.Items[toolStrip.Items.Count - 1].CanSelect)
                AddToolStripSeparator(toolStrip);

            AddToolStripButton(toolStrip, ToolBarButtons.Close);
        }

        private static bool ContainsButton(ToolBarButtons combined, ToolBarButtons checkagainst)
        {
            return ((combined & checkagainst) == checkagainst);
        }

        private static void AddToolStripButton(ToolStrip toolStrip, ToolBarButtons buttonType)
        {
            var newButton = new ToolStripButton();
            string imageName = "", text = "";

            switch (buttonType)
            {
                case ToolBarButtons.Save:
                    {
                        text = SaveText;
                        imageName = NamespaceName + ".Images.tb_save.png";
                        break;
                    }

                case ToolBarButtons.SaveClose:
                    {
                        text = SaveCloseText;
                        imageName = NamespaceName + ".Images.tb_saveclose.png";
                        break;
                    }
                case ToolBarButtons.Delete:
                    {
                        text = DeleteText;
                        imageName = NamespaceName + ".Images.tb_delete.png";
                        break;
                    }
                case ToolBarButtons.New:
                    {
                        text = NewText;
                        imageName = NamespaceName + ".Images.tb_add.png";
                        break;
                    }
                case ToolBarButtons.Edit:
                    {
                        text = EditText;
                        imageName = NamespaceName + ".Images.tb_edit.png";
                        break;
                    }
                case ToolBarButtons.Search:
                    {
                        text = SearchText;
                        imageName = NamespaceName + ".Images.tb_search.png";
                        break;
                    }
                case ToolBarButtons.Print:
                    {
                        text = PrintText;
                        imageName = NamespaceName + ".Images.tb_print.png";
                        break;
                    }
                case ToolBarButtons.Approve:
                    {
                        text = ApproveText;
                        imageName = NamespaceName + ".Images.tb_apply.png";
                        break;
                    }
                case ToolBarButtons.Close:
                    {
                        text = CloseText;
                        imageName = NamespaceName + ".Images.tb_close.png";
                        break;
                    }
            }

            // Lee imagen de los resources del assembly
            imageStream = assembly.GetManifestResourceStream(imageName);
            newButton.Text = text;
            newButton.Name = text;
            if (imageStream != null)
                newButton.Image = Image.FromStream(imageStream);
            newButton.TextAlign = ContentAlignment.BottomCenter;
            newButton.TextImageRelation = TextImageRelation.ImageAboveText;
            newButton.ImageScaling = ToolStripItemImageScaling.SizeToFit;
            newButton.AutoSize = true;
            newButton.Tag = buttonType;

            toolStrip.Items.Add(newButton);
        }

        private static void AddToolStripSeparator(ToolStrip toolStrip)
        {
            var separator = new ToolStripSeparator();
            separator.Tag = ToolBarButtons.None;
            toolStrip.Items.Add(separator);
        }

        protected static void ConfigureGrid(UltraGridBase listGrid)
        {
            listGrid.DisplayLayout.Bands[0].Columns["id"].Hidden = true;
            listGrid.DisplayLayout.Bands[0].Override.CellClickAction = CellClickAction.RowSelect;
            listGrid.DisplayLayout.AutoFitStyle = AutoFitStyle.ExtendLastColumn;
        }

        protected static void ClearControls(Control.ControlCollection controls)
        {
            foreach (Control ctr in controls)
            {
                if (ctr.GetType().ToString().IndexOf("TextBox") > -1 || ctr.GetType().ToString().IndexOf("NumBox") > -1)
                    ctr.Text = "";

                else if (ctr.GetType().ToString().IndexOf("Label") > -1)
                {
                    if (ctr.Tag != null)
                        ctr.Text = ctr.Tag.ToString();
                }
                else if (ctr.GetType().ToString().IndexOf("ComboBox") > -1)
                {
                    var combo = (ComboBox)ctr;
                    combo.SelectedIndex = -1;
                    combo.SelectedIndex = -1;
                }
                else if (ctr.GetType().ToString().IndexOf("DateTimePicker") > -1)
                    ((DateTimePicker)ctr).Value = DateTime.Now;

                else if (ctr.GetType().ToString().IndexOf("CheckBox") > -1 || ctr.GetType().ToString().IndexOf("RadioButton") > -1)
                    ((CheckBox)ctr).Checked = false;

                if (ctr.Controls.Count > 0)
                    ClearControls(ctr.Controls);
            }
        }

        protected static bool IsUniqueName(TipoEntidad entityType, string name)
        {
            var entity = new BCEntidad(entityType).GetItemByName(name);
            return !(entity != null && entity.Nombre == name);
        }

        #endregion
        
    }
}
